#include "Thread.h"

SK


Thread::Thread (Event *completeEvent)
: completeEvent(completeEvent)
{
    state = 0;
    this->th=CreateThread (NULL,0, (LPTHREAD_START_ROUTINE)&_threadStart, (void *)this,CREATE_SUSPENDED,NULL);
}

Thread::Thread (THREAD_START_PROC proc, void *param)
: completeEvent(NULL)
{
    state = 0;
    this->th=CreateThread (NULL,0, (LPTHREAD_START_ROUTINE)proc, param,CREATE_SUSPENDED,NULL);
    if (completeEvent)
        delete completeEvent;
}

Thread::~Thread ()
{
   this->terminate ();
}

void Thread::_runTask (void)
{
    while (this->state != 3)
    {
        tsk->_taskStart();
        InterlockedExchange ((LONG *)&this->state, 0);
        tsk= NULL;
        if (completeEvent)
            completeEvent->signal();

        this->suspend();
    }
}



u32 Thread::getState (void)
{
    return state;
}

bool Thread::isRunning (void)
{
    return state==1;
}


DWORD Thread::_threadStart(void* param)
{
    Thread *t = static_cast <Thread *>(param);
    t->_runTask();
    return 0;
}


void Thread::start (Task *task)
{
    this->tsk = task;
    InterlockedExchange ((LONG *)&this->state, 1);
    this->resume();
}

void Thread::suspend (void)
{
	SuspendThread (this->th);
}

void Thread::resume (void)
{
	ResumeThread (this->th);
}

void Thread::terminate (void)
{
	if (th)
	{
		TerminateThread (this->th, 1);
		CloseHandle (this->th);
	}
}

EK